import base64
import json
import pickle

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.users.models import Address
from utils.response_code import RETCODE


class CartsView(View):
    # 读取
    def get(self,request):
        user = request.user
        # 登陆用户  保存在redis中
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')

            # hash数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # set数据
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
        #转换成carts类型的数据  将redis数据转换成cookie形式
            cart_dict = {}
            # 对redis数据进行遍历来转换为carts类型的数据
            for sku_id, count in  redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }


        #  未登陆用户 保存在cookie中
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 有数据的 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str))
            else:
                # 没有数据的定义一个空字典
                cart_dict = {}
        # 根据id进行商品查询
        sku_ids = cart_dict.keys()
        # skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for id in sku_ids:
            sku = SKU.objects.get(id=id)
        # 将对象转换为字典
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'price':str(sku.price),
                'default_image_url': sku.default_image.url,
                'selected':str(cart_dict[sku.id]['selected']),
                'count': cart_dict[sku.id]['count'],
                'amount': str(sku.price * cart_dict[sku.id]['count']),
            })

        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)



        # """购物车管理"""
    # 添加
    def post(self, request):
        """添加购物车"""
        # 接收和校验参数
        # 判断用户是否登录
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)


        if not all([sku_id, count]):
            return http.HttpResponseBadRequest('缺少必传参数')

        # 判断商品id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('商品不存在')
            # 判断count是否为数字
        try:
            count = int(count)
        except Exception:

            return http.HttpResponseBadRequest('参数count有误')
            # 判断selected是否为bool值

        user = request.user
        # 用户是否存在 且验证
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            # 链接redis数据库
            redis_conn = get_redis_connection('carts')
            # 操作hash
            # redis_conn.hset(key,field,value)
            redis_conn.hset('carts_%s'%user.id,sku_id,count)
            # set
            if selected:
                # redis_conn.sadd(key,memble)
                redis_conn.sadd('selected_%s'%user.id,sku_id)

            # 返回响应
            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})

            pass
        else:
            # 用户未登录，操作cookie购物车
            #先读取cookie数据,并判断carts是否存在
            cookie_str = request.COOKIES.get('carts')
            if cookie_str is not None:
            #说明存在  解码数据
                decode = base64.b64decode(cookie_str)
                carts = pickle.loads(decode)
            else:
                carts={}

            if sku_id in carts:
            #     sku_id 在carts中,则累加数量
                orginal_count = carts[sku_id]['count']
                count += orginal_count



            # 1.组织cookie数据
            carts[sku_id] = {
                'selected': selected,
                'count': count
            }

            # carts ={sku_id:{'selected':'count'}}
            # 2.对cookie数据进行编码
            by = pickle.dumps(carts)
            encode = base64.b64encode(by)
            response = http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})
            # 3.设置cookie数据
            response.set_cookie('carts',encode,max_age=3600)
            # 4.返回响应
            return response
    # 修改
    def put(self,request):
        # 接受用户数据
        user = request.user
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)



        # 判断商品 和 数量是为空
        if not all([sku_id, count]):
            return http.JsonResponse({'code': RETCODE.PARAMERR})

        #判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)

        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('商品不存在')
            # 判断count是否为数字

        # 判断用户是否认证    登陆用户操作redis
        if user.is_authenticated:
            # 链接redis
            redis_conn = get_redis_connection('carts')
            # 更新hash数据
            redis_conn.hset('carts_%s'%user.id, sku_id, count)
            #更新set数据
            if selected:
                # 增加数据
                redis_conn.sadd('selected_%s'%user.id,sku_id)
            else:
                # 移除数据
                redis_conn.srem('selected_%s'%user.id,sku_id)

            # 返回响应
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }


            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})

        # 未登陆用户操作cookie
        else:
           # 获取cookie信息
           cart_str = request.COOKIES.get('carts')
           if cart_str:
                # 对获取的cookie数据进行解码 转化为字典
                cart_dict = pickle.loads(base64.b64decode(cart_str))
           else:
                cart_dict = {}

            # 组织cookie数据

           cart_dict[sku_id] = {
               'count': count,
               'selected': selected
           }
           # 对字典数据进行编码处理 将字典转成bytes,在将bytes转成base64,最后将bytes转成字符串
           cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict))

            # 创建响应对象
           cart_sku = {
               'id': sku_id,
               'count': count,
               'selected': selected,
               'name': sku.name,
               'default_image_url': sku.default_image.url,
               'price': sku.price,
               'amount': sku.price * count,
           }

           response = http.JsonResponse({'code':RETCODE.OK,'errmsg':'修改购物车成功','cart_sku':cart_sku})
           # 设置cookie
           response.set_cookie('carts',cookie_cart_str,max_age=3600)

           # 返回响应
        return response

    # 删除
    def delete(self,request):
        #1.接收数据据   sku_id
        user = request.user
        # 先对接受的数据进行解码   然后在把解码后的数据转成字典类型
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 3.获取用户信息，进行用户信息判断    # 4.登陆用户操作redis
        if user.is_authenticated:
            try:
                # 2.验证数据
                sku = SKU.objects.get(id=sku_id)
            except SKU.DoesNotExist:
                return http.HttpResponseBadRequest("商品不存在")

            else:
                # 链接redis
                redis_conn = get_redis_connection('carts')
                # 删除键，就等价于删除了整条记录
                redis_conn.hdel('carts_%s' % user.id, sku_id)
                # 移除set里面的数据
                redis_conn.srem('selected_%s' % user.id, sku_id)

                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

       # 5.未登陆用户操作cookie
        else:
            # 获取cookie数据
            car_str = request.COOKIES.get('carts')
            if car_str:
                #如过有cookie数据   进行解码
                cart_dict = pickle.loads(base64.b64decode(car_str))
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                # 删除商品id
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64
            encode = base64.b64encode(pickle.dumps(cart_dict))
            response = http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})
            response.set_cookie('carts',encode,max_age=3600)
        return response











